#!/usr/bin/env python3
'''
Merge tables with header.
Author: liqiming@whu.edu.cn
'''
import argparse
import pandas as pd
from .utils import table2df, df2table


def main(table_list, outfile):
    df_list = []
    for table in table_list:
        df_list.append(table2df(table))
    out_df = pd.concat(df_list)

    if outfile:
        df2table(outfile, out_df)
    else:
        print("\t".join(map(str, out_df.columns)))
        for _, row in out_df.iterrows():
            print("\t".join(map(str, dict(row).values())))


def run():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("input", type=str, nargs="+",
                        help="Input tables with header you need to merge, separated by spaces.")
    parser.add_argument("-o", dest="output", type=str, default=None,
                        help="Output file, discard this parameter to print output to stdout.")
    args = parser.parse_args()
    main(args.input, args.output)


if __name__ == "__main__":
    run()
